package mwa.cs.rc.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.UserLoginDAO;
import mwa.cs.database.Database;

/**
 * Servlet implementation class CS56001Srvl
 */
public class CS56001Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;

    public CS56001Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		HttpSession session = request.getSession();
		
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		if (request.getParameter("process_type").equals("getEmployee")) {

			Database db = new Database();

			try {
				UserLoginDAO voUserLogin = new UserLoginDAO(db);
				List<Map<String, Object>> voResult = voUserLogin.findAllUserNameBySiteId(vnSiteId);
		
				String[] vaValue = new String[voResult.size()];
				String[] vaMessage = new String[voResult.size()];

				for (int i = 0; i < voResult.size(); i++) {
					Map<String, Object> voObject = voResult.get(i);	
					vaValue[i] = (String) voObject.get("USER_ID").toString(); 
					vaMessage[i] = ((String)voObject.get("USER_PNAME").toString())+" "
									+((String)voObject.get("USER_FNAME").toString())+" "
									+((String)voObject.get("USER_LNAME").toString());	
				}
				
				JSONObject voObject = new JSONObject();
				JSONArray voList = new JSONArray();
				PrintWriter voOut = response.getWriter();
				if (vaMessage != null) {
					for (int i = 0; i < vaMessage.length; i ++) {
						voList.add(vaMessage[i]);
					}
				}
				voObject.put("messages", voList);
				JSONArray voList2 = new JSONArray();
				if (vaValue != null) {
					for (int i = 0; i < vaValue.length; i ++) {
						voList2.add(vaValue[i]);
					}
				}

				voObject.put("values", voList2);

				voOut.print(voObject.toJSONString());
			} catch (Exception e) {
				e.printStackTrace();
			} finally{
				db.close();
			}
			
		}
		
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
